import * as signalR from '@microsoft/signalr';

/**
 * 初始化socket对象
 * @param connect 接受消息的处理方法 
 * (message: string 消息内容, returnUrl: string 调整路径, key: string 消息分组key, appId: string 应用ID) => void
 * @param fn 额外初始化后执行的逻辑
 * @returns socket 连接对象
 */
export const initSocket = (connect: (message: string, returnUrl: string, key: string, appId: string) => void, fn?: Function) => {
  // 初始化连接对象
  const socket = new signalR.HubConnectionBuilder()
    .withUrl('/inbiz/api/services/front/hub/Message')
    .withAutomaticReconnect()
    .build();
  // 连接方法
  startSocket(socket, connect)
  // 额外初始化逻辑
  fn?.()
  // 断开重连
  socket.onclose(() => {
    socket.off('ReceiveMessage');
    // 连接方法
    startSocket(socket, connect)
  });
  return socket
}

/**
 * 发起socket连接
 * @param socket 连接对象
 * @param callback 接收消息的处理方法
 */
const startSocket = (socket: any, callback: any) => {
  socket?.on(
    'ReceiveMessage',
    callback
  );
  socket?.start().then().catch(() => { });
}

/**
 * 销毁socket
 * @param socket 连接对象
 */
export const destroySocket = (socket?: any) => {
  socket?.off('ReceiveMessage');
  socket?.stop().then().catch(() => { });
}
